#!/bin/dash

# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

. /usr/lib/connectivity-common.sh

OCF=org.chromium.flimflam
MASKED_PROPERTIES="
  Address
  Cellular.ESN
  Cellular.ICCID
  Cellular.IMEI
  Cellular.IMSI
  Cellular.MDN
  Cellular.MEID
  Cellular.MIN
  Cellular.UsageUrl
  EAP.AnonymousIdentity
  EAP.CACertID
  EAP.CACertNSS
  EAP.CertID
  EAP.EAP
  EAP.Identity
  EAP.InnerEAP
  EAP.KeyID
  EAP.PIN
  EAP.PrivateKey
  EAP.SubjectMatch
  Name
  WiFi.BSSID
  WiFi.HexSSID
  WiFi.SSID
"
MASKED_PROPERTIES_PATTERN=$(echo ${MASKED_PROPERTIES} | sed 's/ /|/g')

mask_properties() {
  sed -E "s/\<(${MASKED_PROPERTIES_PATTERN}): (.+)/\1: *** MASKED ***/i"
}

# Returns a list of flimflam objects of the specified kind.
get_flimflam_objects() {
  # NB: add s to pluralize kind
  local kind="${1}s"
  local filter="$2"

  dbus_call "${OCF}" / "${OCF}.Manager.GetProperties" \
    | extract_dbus_match "${kind}" \
    | grep "${filter}"
}

print_properties() {
  local kind="$1"
  local object="$2"

  dbus_call "${OCF}" "${object}" "${OCF}.${kind}.GetProperties" | stripindexes
}

normalize_kind() {
  local kind="${1%s}"  # Remove trailing s

  case "${kind}" in
    [Ss]ervice)
      echo -n Service
      ;;
    [Dd]evice)
      echo -n Device
      ;;
    *)
      error_exit "Did not understand connection manager entity ${kind}."
      ;;
  esac
}

show() {
  $(needarg raw_kind)
  $(arg_or_default filter .)

  local kind=$(normalize_kind "${raw_kind}")
  local objects="$(get_flimflam_objects ${kind} ${filter})"

  for object in ${objects}; do
    echo "${object}"
    print_properties "${kind}" "${object}"
    echo
  done
}

usage() {
  cat <<EOF
Usage: $0 <command> [args...]
  show {Devices|Services} [-filter regex]
        Show these objects and their properties: If a filter is supplied,
        use it to filter object names.
EOF
  exit
}

$(needarg cmd)
case "$cmd" in
  show)
    show "$@"
    ;;
  show-feedback)
    show "$@" | mask_properties
    ;;
  *)
    usage
    ;;
esac
